<link rel="stylesheet" href="__STATIC__/layui/css/layui.css"  media="all">

<script type="text/javascript">
if(typeof(layui)=='undefined'){
	document.write('<script type="text/javascript" src="__STATIC__/layui/layui.js"><\/script>');
}
var tree_data = JSON.parse( $("#atc_options").val()!='' ? $("#atc_options").val() : '[{"id":"80348","title":"分类一"},{"id":"80349","title":"分类二"}]' );

var Tree;

$(function(){

	$("#atc_addsorts").after('<span class="layui-btn layui-btn-normal layui-btn-sm" id="sort_add">添加一级分类</span> <div id="treewarp"></div>');
	$("#atc_addsorts").remove();
	layui.use('tree', function(){
		Tree = layui.tree;
		//渲染
		var inst1 = Tree.render({
			elem: '#treewarp'  //绑定元素
			,id: 'optionId' //定义索引
			,showCheckbox:false
			,edit:['add','update', 'del']
			,accordion:false
			,data: tree_data
			,operate: function(obj){
				setTimeout(function(){
					//console.log( JSON.stringify( get_tree_value($("#treewarp .layui-tree")) , null, 2) )
					$("#atc_options").val( JSON.stringify(get_tree_value($("#treewarp .layui-tree"))) );
				},200);
				var type = obj.type; //得到操作类型：add、edit、del
				var data = obj.data; //得到当前节点的数据
				var elem = obj.elem; //得到当前节点元素			
				var id = data.id; //得到节点索引			
				if(type === 'add'){ //增加节点
					elem.children(".layui-tree-pack").show(200);
				} else if(type === 'update'){ //修改节点
					//if(elem.attr('data-id')=='undefined' || elem.attr('data-id')<10000){elem.attr('data-id',create_num());}
				} else if(type === 'del'){ //删除节点
				}
			}
		});
		//var checkData = tree.getChecked('optionId');
	});

	$('#sort_add').click(function(){
		layer.prompt({
						title: '请输入分类名称',
						formType: 0
		}, function(value){
					 if(value==''){
						return ;
					 }
					 layer.closeAll();
					 tree_data.push({title:value});
					 Tree.reload('optionId', {data: tree_data});
					 $("#atc_options").val( JSON.stringify(get_tree_value($("#treewarp .layui-tree"))) );
					 //console.log( JSON.stringify( get_tree_value($("#treewarp .layui-tree")) , null, 2) )
		});
	});
});

function get_tree_value(obj){
	var ar = [];
	obj.children(".layui-tree-set").each(function(){
		var id = $(this).attr("data-id");
		if(id=='undefined' || id<10000){
			id = (new Date()).getTime().toString().substring(8,13);
			if(id<10000){
				id = parseInt(id) + 10000;
			}
			$(this).attr("data-id",id);
		}
		var o ={id:id,title:$(this).find(".layui-tree-entry .layui-tree-main .layui-tree-txt").html()};
		if($(this).children(".layui-tree-pack").length>0){
			o.children = get_tree_value( $(this).children(".layui-tree-pack").eq(0) );
		}
		ar.push(o);	
	});
	return ar;
}
</script>